import type { ExternalProvider } from '@ethersproject/providers'
import type { MetaMaskInpageProvider } from '@metamask/providers'
import { ethers } from 'ethers'
import MetaMaskOnboarding from '@metamask/onboarding'

/**
 * Creates a metamask based provider
 * @returns
 */

export const initMetamask = async () => {
  const { ethereum } = window
  if (!ethereum || !ethereum.isMetaMask) {
    const onboarding = new MetaMaskOnboarding({ forwarderOrigin: window.location.origin })
    onboarding.startOnboarding()
    throw new Error('Ethereum missing')
  }
  const externalProvider = ethereum as unknown as ExternalProvider & MetaMaskInpageProvider
  const provider: ethers.providers.Web3Provider = new ethers.providers.Web3Provider(
    externalProvider,
    'any',
  )
  const signer = provider.getSigner()
  return { provider, signer, externalProvider }
}
